package org.pathlet.core.impl;

import org.pathlet.core.Path;
import org.pathlet.core.PathletResource;

import java.util.*;

public class PathletResourceCache {

    private Map<Path, PathletResource> cache = new HashMap<Path, PathletResource>();

    private Map<String, Path> typeCache = new HashMap<String, Path>();

    private Map<Path, List<String>> pathTypeCache = new HashMap<Path, List<String>>();

    public void put(Path path, PathletResource resource) {
        cache.put(path, resource);
        Class type = resource.getTargetType();
        if(type != null) {
            //add type className
            String typeName = type.getName();
            addType(path, typeName);

            //add type's interfaces
            Class[] interfaces = type.getInterfaces();
            for(Class itf : interfaces) {
                addType(path, itf.getName());
            }
        }
    }

    public PathletResource get(Path path) {
        return cache.get(path);
    }

    public void remove(Path path) {
        cache.remove(path);
        List<String> types = pathTypeCache.remove(path);
        if(types != null) {
            for(String type : types) {
                typeCache.remove(type);
            }
        }
    }

    public void clear() {
        cache.clear();
        typeCache.clear();
        pathTypeCache.clear();
    }

    public boolean contains(Path path) {
        return cache.containsKey(path);
    }

    public Set<Path> getPathsSet() {
        return cache.keySet();
    }

    public Path getPath(String typeClassName) {
        return typeCache.get(typeClassName);
    }

    private void addType(Path path, String typeName) {
        typeCache.put(typeName, path);
        List<String> types = pathTypeCache.get(path);
        if(types == null) {
            types = new ArrayList<String>();
            pathTypeCache.put(path, types);
        }
        types.add(typeName);
    }

}
